<?php
class AdminPostsController extends AppController {
	
	//set name of the layout
	public $layout='admin';
	
	public $helpers = array (
			'Html',
			'Session'
	);
	
	public function index($userId = null) {
		if(!$userId) {
			return $this->render('/errors/error');
		}
		
		//initiate session check authority
		$this->Session->write('author', false);
		
		//call method check login
		$checkLogin = $this->checkLogin();
		
		//check authority
		if(is_array($checkLogin)) {
			if($userId == $checkLogin['loginId']) {
				//user has full authority on profile.ctp
				$this->Session->write('author', true);
			}
		}
		
		$this->loadModel('Post');
		$allPost = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.user_id' => $checkLogin ['loginId']
				)) );
		//set data for profile.ctp
		$this->set('allCreatedPosts', $allPost);
	}
	
	/**
	 * Method transit to profile.ctp
	 */
	public function profile() {

		$isAdmins = false;
		
		//TODO use routter to rewrite url for this action (profile)
		$userId = $this->request->params['pass'][0];
		
		//check acl if role is user, alow it to manage its own posts,
		//if role is admin, alow it to manage all posts
		if ($this->Acl->check ( $this->Auth->user ( 'role' ), 'manageAllPost')){
			$isAdmins = true;
		}
		
		//check parameter
		if(!$userId) {
			return $this->render('/errors/error');
		}
		
		//initiate variable check authority
		$isAuthor = 0;
		
		//call method check login
		$checkLogin = $this->checkLogin();
		
		//check authority
		
		if(is_array($checkLogin)) {
			if($userId == $checkLogin['loginId']) {
				//user has full authority on profile.ctp
				$isAuthor=1;
			}
		}
						
		$this->loadModel('User');
		//set data for profile.ctp
		$this->set('user', $this->User->findByid($userId));
		$this->loadModel('Post');
		$this->set('created', $this->Post->findAllCreatedPost($userId));
		
		//set data for profile.ctp		
		$this->set('isAuthor',$isAuthor);
		$this->set('posts', $this->getAllDataPaging($userId, $isAdmins));
		$this->set('chartData', $this->getChartData($userId));
	}

	/**
	 * Method add post
	 */
	public function add() {
		
		
		
		//check login
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
		$this->loadModel('Post');
		$this->loadModel('User');
		// save to db
		if ($this->request->is( 'post' )) {
			$this->Post->create();
			
			$createdUser = $this->request->data;
			$createdUser['user_id'] = $this->Auth->user('id');
			
			if ($this->Post->save ( $createdUser )) {
				
				// search id for redirect to view.ctp
				$newPost = $this->Post->find ( 'first', array (
						'conditions' => array (
								'Post.user_id' => $checkLogin ['loginId']
						),
						'order' => 'Post.modified DESC'
				) );
				
				
				$this->Session->setFlash ( 'Your post has been saved', 'default', array (
						'class' => 'alert alert-success'
				) );
	
				return $this->redirect ( array (
						'controller' => 'posts',
						'action' => 'detail',
						$newPost ['Post'] ['id'],
						'?' => array (
								'b' => 'm'//flag for backDestination
						)
				) );
			}
			$this->Session->setFlash ( 'Unable to save your post', 'default', array (
					'class' => 'alert alert-danger'
			) );
			
		}
	}
	private function upload() {
		/* form submitted? */
		if ($this->request->is('post')) {
			$filename = "app/webroot/files/".$this->data['thumbnail']['name']; 
           /* copy uploaded file */
			if (move_uploaded_file($this->data['thumbnail']['tmp_name'],$filename)) {
				/* save message to session */
				//$this->Session->setFlash('File uploaded successfuly. You can view it <a href="/app/webroot/files/'.$this->data['Pages']['file']['name'].'">here</a>.');
				/* redirect */
				//$this->redirect(array('action' => 'index'));
			} else {
				/* save message to session */
				//$this->Session->setFlash('There was a problem uploading file. Please try again.');
			}
		}
		//$this->render('home');
	}
	
	/**
	 * Method edit post
	 */
	public function edit($id = null) {
		//check login
		
		
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
		
		//check if the current user is admin
		$isAdmins = false;
		if ($this->Acl->check ( $this->Auth->user ( 'role' ), 'manageAllPost')){
			$isAdmins = true;
		}
		
		// check params
		if (!$id) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
		
		//Load model Post
		$this->loadModel('Post');
		$post = $this->Post->findById ( $id );
		if (! $post) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
	
		// check is Author tanthm
		if($isAdmins == false){
			if(is_array($checkLogin)) {
				if($post['Post']['user_id'] !== $checkLogin['loginId']) {
					return $this->render('/errors/error');
				}
			}
		}
		
		// save to db
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			if($isAdmins || $post['Post']['user_id'] == $checkLogin['loginId']) {
				$this->Post->id = $id;
				if ($this->Post->save ( $this->request->data )) {
					$this->Session->setFlash ( 'Your post has been updated', 'default', array (
							'class' => 'alert alert-success'
					) );
					
					return $this->redirect ( array (
							'controller' => 'posts',
							'action' => 'detail',
							$id
					) );
				}
			}else{
				$this->Session->setFlash ( "You can't update this post ", 'default', array (
						'class' => 'alert alert-danger'
				) );
			}
		}
		// initialize value if update date is not available
		if (! $this->request->data) {
			$this->request->data = $post;
		}
		// reder view layout for edit
		$this->set ( 'post', $post );
	}
	
	/**
	 * Method delete post
	 */
	public function delete($id = null) {
		//check login
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
	
		// check request method, if not 'Post' throw error
		if ($this->request->is ( 'get' )) {
			throw new MethodNotAllowedException ();
		}
	
		//check if the current user is admin
		$isAdmins = false;
		if ($this->Acl->check ( $this->Auth->user ( 'role' ), 'manageAllPost')){
			$isAdmins = true;
		}
		
		// delete data in db, cascade setting help delete depedent child data
		$this->loadModel('Post');
		
		// check is Author tanthm
		if(is_array($checkLogin)) {
			if( $isAdmins !== true && $post['Post']['user_id'] !== $checkLogin['loginId']) {
				return $this->render('/errors/error');
			}
		}
		
		if ($this->Post->delete ( $id )) {
			$this->Session->setFlash ( 'Deleted', 'default', array (
					'class' => 'alert alert-success'
			) );
			return $this->redirect ( array (
					'controller' => 'adminposts',
					'action' => 'profile',
					$checkLogin['loginId']
			) );
		}
	}
	
	/**
	 * Method search for admin
	 */
	public function search() {
		
	}
	
	/**
	 * Method escape special symbols
	 */
	private function escape($str = null) {
		if(!$str) {
			return $this->render('/errors/error');
		}
		return $this->render('/adminposts/profile/1');
	}
	
	/**
	 * Method check login
	 */
	private function checkLogin() {
		if($this->Session->check('Auth.User')) {
			$user = $this->Session->read('Auth.User');
			return array(true,'loginId' => $user['id']);
		}
		return false;
	}
	
	/**
	 * Method check whether user exists
	 */
	private function checkUserExist($userId = null) {
		$check = $this->Admin->find('all',array('conditions' => array('Admin.AdminID' => $id)));
		if(!$check) {
			return $this->render('/errors/error');
		}
	}
	
	/**
	 * Method get paging
	 */
	private function getAllDataPaging($userId = null, $isAdmin = false) {
		
		$condition =  array('Post.user_id' => $userId);
		
		//if isAdmin is true, set condition to null to get all posts
		if($isAdmin == true){
			$condition = null;
		}
		
		$this->paginate = array(
				'conditions' => $condition,
				'limit' => 10,
				'order' => 'Post.modified DESC'
		);
		try {
			return $this->paginate ( 'Post' );
		} catch ( NotFoundException $e ) {
			return $this->render('/errors/error');
		}
	}
	
	/**
	 * Method get data for chart
	 */
	private function getChartData($userId = null) {
		// find all the date this user create post, group by created date
		$results = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.user_id' => $userId
				),
				'fields' => array (
						'DATE(Post.created) AS created',
						'COUNT(*) AS quantity'
				),
				'group' => array (
						'DATE(Post.created)'
				),
				'order' => array (
						'DATE(Post.created) ASC'
				)
		) );
	
		// group the result again, this time by month_year
		$monthYearGroup = array ();
		App::uses ( 'CakeTime', 'Utility' );
		$dummyStr = "";
		$tempCount = 0;
	
		for($i = 0; $i < sizeof ( $results ); $i ++) {
			$rTime = CakeTime::format ( $results [$i] [0] ['created'], '%B_%Y' );
	
			//check whether the value month_year is stored in $monthYearGroup array, use another temp string
			if (strpos ( $dummyStr, $rTime ) === false) {
				$dummyStr = $dummyStr . $rTime . ' ';
	
				// sum the quantity of equal-month_year records
				for($j = $i; $j < sizeof ( $results ); $j ++) {
					$rTimeChild = CakeTime::format ( $results [$j] [0] ['created'], '%B_%Y' );
	
					if ($rTimeChild == $rTime) {
						$tempCount = $tempCount + $results [$j] [0] ['quantity'];
					} else {
						break;
					}
				}
	
				// store the new month_year time and quantity into array
				array_push ( $monthYearGroup, array (
				'dateTime' => $rTime,
				'quantity' => $tempCount
				) );
				$tempCount = 0;
			}
		}
	
		//json encode for data chart
		$chartData ['cols'] = array (
				array (
						'id' => 'created',
						'label' => 'Date',
						'type' => 'string'
				),
				array (
						'id' => 'quantity',
						'label' => 'Posted',
						'type' => 'number'
				)
		);
		foreach ( $monthYearGroup as $result ) {
			$row = array (
					'c' => array (
							array (
									'v' => $result ['dateTime']
							),
							array (
									'v' => $result ['quantity']
							)
					)
			);
			$chartData ['rows'] [] = $row;
		}
		return json_encode ( $chartData ) ;
	}
	
/* 	public function isAuthorized($user = null){
		
		if ($this->Auth->user ()) {
			// chech if current user is authorized
			if ($this->Acl->check ( $this->Auth->user ( 'role' ), $this->params ['controller'] )) {
				$this->Auth->allow ( 'profile','add','edit','delete');
			}
		}
	} */
	
	 public function beforeFilter() {
		parent::beforeFilter();
	
		 if ($this->Auth->user ()) {
			// chech if current user is authorized
			if ($this->Acl->check ( $this->Auth->user ( 'role' ), $this->params ['controller'] )) {
				$this->Auth->allow ( 'profile','add','edit','delete');
			}
		} 
	} 
}